<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>发送ajax请求</title>
<body>
<button>发送ajax请求</button>
<script>
    //1.获取DOM元素对象
    let btn = document.querySelector('button');
    //2.绑定事件
    btn.onclick = function(){
        //3.创建promise实例对象
        const p = new Promise((resolve,reject)=>{
            //4.创建ajax实例对象
            const xhr = new XMLHttpRequest();
            //5.打开请求
            xhr.open('get','http://localhost:7008/cars');
            //6.发送请求
            xhr.send();
            //7.利用onreadystatechange事件
            xhr.onreadystatechange = function(){
                //8.判断
                if(xhr.readyState == 4){
                    if(xhr.status == 200){
                        resolve(xhr.responseText);
                    }else{
                        reject(xhr.response);
                    }
                }
            }
        });

        p.then(value=>{
            console.log("==> ");
            console.log(JSON.parse(value));
        },reason=>{
            console.log('获取信息失败');
        })
    }
</script>
</body>
</html>
